import { shell, app, remote } from "electron";
import protocolConfig, { Akaba } from "../var/protocolConfigFunc";
import URL from "url";
export namespace NAppFunc {
}

export function openURLInExplorer(url: string) {
    if (url && url.trim()) {
        return shell.openExternal(getOriginURL(url));
    }
    return Promise.resolve();
}

export function getOriginURL(url: string) {
    const urlObj = URL.parse(url);
    const protocol = urlObj.protocol;
    const protocolObj = getCustomProtocol(protocol);
    if (protocolObj) {
        url = URL.format({
            slashes: true,
            protocol: protocolObj.type,
            pathname: protocolObj.getPath(url),
        });
    }
    return url;
}

export function getCustomProtocol(prefix: string): Akaba.ProtocolConfigConfigObj | false {
    const match = prefix.match(/^\w+/);
    if (match) {
        prefix = match[0];
    }
    if (protocolConfig.hasOwnProperty(prefix)) {
        return protocolConfig[prefix];
    }
    return false;
}

export function getAppObj() {
    if (app) {
        return app;
    }
    return remote.app;
}
